/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';
import React, {
  AppRegistry,
  Component,
  StyleSheet,
  Text,
  View,
  Navigator,
  BackAndroid,
  Dimensions,
  TouchableOpacity,
  Image,
  ListView,
  DeviceEventEmitter,
  AsyncStorage,

} from 'react-native';
import RNFileSearch from './RNFileSearch';
import ProgressBarAndroid from 'ProgressBarAndroid';
import Storage from 'react-native-storage';
var FileTransfer = require('@remobile/react-native-file-transfer');
var TimerMixin = require('react-timer-mixin');
import MainScreen from './MainScreen';
var width = Dimensions.get('window').width;
// import DownloadCenter from './DownloadCenter';
var b =[];

class DownloadControl extends React.Component {
  constructor(props) {
    super(props);
    this.state={
      mixins: [TimerMixin],
      dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2}),
      upstatus: this.props.uploadList,  //标记上传状态还是下载状态
      downloadCenter: this.props.downloadCenter
    }
  }
 componentWillMount(){
   this.fetchData();
 }
  componentDidMount(){

  }
  componentWillUnmount() {
    this.uploadTimer && TimerMixin.clearInterval(this.uploadTimer);
    this.downloadTimer && TimerMixin.clearInterval(this.downloadTimer);
  }

  fetchData(){ //主页面传过来的数据
    if (this.state.upstatus) {
      this.uploadTimer = TimerMixin.setInterval(()=>{
        // console.log('当前上传任务的长度：'+this.state.downloadCenter.getCurDataList(true).length);
        // console.log('数据是：',this.state.downloadCenter.getCurDataList(true));
        b=this.state.downloadCenter.getMergeData(true);
        b.length = 0;
        if(this.state.downloadCenter.getCurDataList(true).length>0){
          this.setState({dataSource:this.state.dataSource.cloneWithRows(this.state.downloadCenter.getMergeData(true))});
          this.state.downloadCenter.clearMergeData(true);
          console.log('上传返回的数据',this.state.downloadCenter.getMergeData(true));
        }else{
          this.setState({dataSource:this.state.dataSource.cloneWithRows(this.state.downloadCenter.getMergeData(true))});
          this.uploadTimer && TimerMixin.clearInterval(this.uploadTimer);
        }
      },500)
    } else {
      this.downloadTimer = TimerMixin.setInterval(()=>{
        console.log('当前下载任务的长度：'+this.state.downloadCenter.getCurDataList(false).length);
        if(this.state.downloadCenter.getCurDataList(false).length>0){
          this.setState({dataSource:this.state.dataSource.cloneWithRows(this.state.downloadCenter.getMergeData(false))});
          console.log('下载返回的数据',this.state.downloadCenter.getMergeData(false),this.state.downloadCenter.getMergeData(false).length);
          this.state.downloadCenter.clearMergeData(false);
        }else{
          this.setState({dataSource:this.state.dataSource.cloneWithRows(this.state.downloadCenter.getMergeData(false))});
          this.downloadTimer && TimerMixin.clearInterval(this.downloadTimer);
        }
      },500)
    }
  }

  goback(){
    const { navigator } = this.props;
    if(navigator) {
        navigator.pop();
    }else{
        console.log("路由为空");
    }
    this.state.downloadCenter.clearMergeData(true)
    this.state.downloadCenter.clearMergeData(false)
    this.uploadTimer && TimerMixin.clearInterval(this.uploadTimer);
    this.downloadTimer && TimerMixin.clearInterval(this.downloadTimer);
  }

  uploadClick(){
    this.downloadTimer && TimerMixin.clearInterval(this.downloadTimer);
    this.state.upstatus = true;
    this.fetchData();
    this.state.downloadCenter.clearMergeData(false)
  }
  downloadClick(){
    this.uploadTimer && TimerMixin.clearInterval(this.uploadTimer);
    this.state.upstatus = false;
    this.fetchData();
    this.state.downloadCenter.clearMergeData(true)

  }
  getLocalTime(time){
   var now = new Date(parseInt(time))
   var year= now.getFullYear();
   var month = now.getMonth()+1;
   var date = now.getDate();
   var hour = now.getHours();
   var minute = now.getMinutes();
   var second = now.getSeconds();
   return   year+"-"+month+"-"+date+"   "+hour+":"+minute+":"+second;
  }
  _renderRow(file,sectionID,rowID){
    console.log(file.updated);
    console.log(file.year);
    var progress =  (<View><ProgressBarAndroid  style={styles.rowProgress}/>
      <Text style={styles.progressPercent}>{(file.progress)+'%'}</Text></View>);
      var image ;
      if(file.icon){
        image = (<View><Image
          source={{uri:file.icon}}
          style={styles.thumbnail}
          ></Image></View>)

        }else{
          image = (<View><Image
            source={require('./img/iconhead.png')}
            style={styles.thumbnail}
            ></Image></View>)
        }

          return(
            <TouchableOpacity onPress={()=>this._pressRow(file,rowID)}>
            <View style={styles.container}>
            {image}
            <View style={styles.rightContainer}>
            <Text style={styles.title} numberOfLines={1}>{file.name || file.title}</Text>
            <Text style={styles.year}>{file.year || this.getLocalTime(file.updated) }</Text>
            </View>
            {file.progress!=100 && progress}
            </View>
            </TouchableOpacity>
          )
        }

  _pressRow(file){
    if(this.state.upstatus){
      if(file.progress==100){
        RNFileSearch.openLocalFile('sdcard/RNdata/'+file.filePath);
      }
    }else{
      if(file.progress==100){
        RNFileSearch.openLocalFile('sdcard/RNdata/'+file.name);
      }
    }
  }

  render() {

    return (
      <View style={{flex:1}}>
        <View style={styles.head}>
          <TouchableOpacity onPress={this.goback.bind(this)}>
            <View style={{justifyContent:'center',marginLeft:15}}>
              <Image
                style={styles.backBtn}
                source={require('./img/back.png')} />
            </View>
          </TouchableOpacity>
          <View style={styles.headTitle}>
            <Text style={{left:105,color:'white'}}>传输列表</Text>
          </View>
        </View>

        <View style={styles.subTitle}>
          <TouchableOpacity onPress={this.uploadClick.bind(this)}>
            <Image
              style={{width:width/2,height:40}}
              source={require('./img/select/bgl.png')} >
              <View style={{marginLeft:100,marginTop:10}}>
                <Text style={[this.state.upstatus && styles.selectedTab]}>上传列表</Text>
              </View>
            </Image>
          </TouchableOpacity>
          <TouchableOpacity onPress={this.downloadClick.bind(this)}>
            <Image
              style={{width:width/2,height:40}}
              source={require('./img/select/bgr.png')} >
              <View style={{marginLeft:25,marginTop:10}}>
                <Text style={[(!this.state.upstatus) && styles.selectedTab]}>下载列表</Text>
              </View>
            </Image>
          </TouchableOpacity>
        </View>

        <View style={styles.listView}>
          <ListView
            dataSource={this.state.dataSource}
            renderRow={this._renderRow.bind(this)}/>
        </View>

      </View>
    );
  }
}

const styles = StyleSheet.create({
  selectedTab:{
    color:'#33AA68',
  },
  head:{
    height:50,
    flexDirection:'row',
    backgroundColor:'#6d9eeb'
  },
  backBtn:{
    width:30,
    height:30,
    marginTop:12
  },
  headTitle:{
    flex:1,
    justifyContent:'center'
  },
  subTitle:{
    flexDirection:'row',
    height:40
  },
  listView:{
    flex:1,
  },
  container: {
    height: 65,
    flexDirection: 'row',
  },
  rightContainer: {
    flex:1,
    marginLeft:8,
  },
  thumbnail: {
    marginTop:10,
    marginLeft:15,
    width: 40,
    height: 50,
  },
  title:{
    marginBottom: 8,
    marginTop:13,
    marginLeft:15,
    width:240,
    color:'black',
    fontSize:16
  },
  year:{
    fontSize: 12,
    marginTop:-5,
    marginLeft:15,
  },
  rowIcon:{
    width:10,
    height:10,
    marginTop:30,
    marginRight:20
  },
   rowProgress:{
    position: 'absolute',
    right: 0
   },
   progressPercent:{
     position: 'absolute',
     right: 10,
     top:15,
   }
})
module.exports = DownloadControl;
